package cn.ahxb.frame.common.base;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.View;

/**
 * Created by xuyougen on 2018/4/17.
 */

public abstract class BaseMvpFragment<V extends BaseView, P extends BasePresenter<V>> extends BaseFragment {

    private Dialog mLoadingDialog;
    private P mPresenter;

    private boolean isDataLoaded = false;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (mLoadingDialog == null)
            mLoadingDialog = createProgressDialog();
        mPresenter = createPresenter();
        mPresenter.attach((V) this);
        initView();
        initData();
        getLazyData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        getLazyData();
        onVisibilityChanged(isVisibleToUser);
    }

    private void getLazyData() {
        if (getUserVisibleHint() && getView() != null) {
            if (!isDataLoaded) {
                lazyLoadData();
                isDataLoaded = true;
            }
        }
    }

    protected abstract void lazyLoadData();

    protected void onVisibilityChanged(boolean isVisibleToUser) {
    }

    protected abstract void initView();

    protected abstract void initData();

    protected abstract P createPresenter();

    public P getPresenter() {
        return mPresenter;
    }

    protected Dialog createProgressDialog() {
        ProgressDialog dialog = new ProgressDialog(getContext());
        dialog.setTitle("请稍等");
        dialog.setCancelable(false);
        dialog.setIndeterminate(true);
        return dialog;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.detach();
    }

    public void showLoadingDialog() {
        mLoadingDialog.show();
    }

    public void hideLoadingDialog() {
        mLoadingDialog.dismiss();
    }
}
